/*
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-09-13 18:17:47
 * @LastEditTime: 2019-09-22 12:54:10
 * @LastEditors: Please set LastEditors
 */
const express = require('express')
const router = express.Router()
const Profile = require('../../models/Profile')
const passport = require('passport')


router.post('/add',passport.authenticate('jwt',{session:false}),function(req,res){
    const profileFiles = {}
    if(req.body.type) profileFiles.type = req.body.type
    if(req.body.descript) profileFiles.descript = req.body.descript
    if(req.body.income) profileFiles.income = req.body.income
    if(req.body.expend) profileFiles.expend = req.body.expend
    if(req.body.cash) profileFiles.cash = req.body.cash
    if(req.body.remark) profileFiles.remark = req.body.remark

    new Profile(profileFiles).save().then(profile=>{
        res.json(profile)
    })

})


router.get('/',passport.authenticate('jwt',{session:false}),(req,res)=>{
    Profile.find()
            .then(profile=>{
                if(!profile){
                    return res.status(400).json('没有任何内容')
                }
                res.json(profile)
            })
            .catch(err => res.status(404).json(err))
})

router.get('/:id',passport.authenticate('jwt',{session:false}),(req,res)=>{
    Profile.findOne({_id:req.params.id})
            .then(profile=>{
                if(!profile){
                    return res.status(400).json('没有任何内容')
                }
                res.json(profile)
            })
            .catch(err => res.status(404).json(err),console.log(req.params.id))
})



// 编辑
router.post('/edit/:id',passport.authenticate('jwt',{session:false}),function(req,res){
    const profileFiles = {}
    if(req.body.type) profileFiles.type = req.body.type
    if(req.body.descript) profileFiles.descript = req.body.descript
    if(req.body.income) profileFiles.income = req.body.income
    if(req.body.expend) profileFiles.expend = req.body.expend
    if(req.body.cash) profileFiles.cash = req.body.cash
    if(req.body.remark) profileFiles.remark = req.body.remark

    Profile.findOneAndUpdate(
        {_id:req.params.id},
        {$set:profileFiles},
        {new:true}
    ).then(profile=>res.json(profile))

})


// 删除
router.post('/delete/:id',passport.authenticate('jwt',{session:false}),function(req,res){
    Profile.findOneAndRemove({
        _id:req.params.id
    }).then(profile=>{
        profile.save().then(profile=>res.json(profile))
    }).catch(err=>{res.status(400).json('删除失败')})
})

module.exports = router